#pragma once

#include<iostream>
#include<pthread.h>

namespace LockModule
{
    class Mutex
    {
        Mutex(const Mutex& m) = delete;//互斥锁是不可拷贝的资源
        Mutex& operator =(const Mutex& m) = delete;//一个互斥锁对象对应操作系统内核中的一个锁实例，拷贝它意味着创建 “两个对象对应同一个内核锁”
    public:
    Mutex()
    {
        int n = pthread_mutex_init(&_mutex, nullptr);
        (void)n;
    }

    void lock()
    {
        int n = pthread_mutex_lock(&_mutex);
        (void)n;
    }

    void unlock()
    {        
        int n = pthread_mutex_unlock(&_mutex);
        (void)n;
    }

    pthread_mutex_t* mutexptr()
    {
        return &_mutex;
    }

    ~Mutex()
    {
        int n = pthread_mutex_destroy(&_mutex);
        (void)n;
    }
    private:
    pthread_mutex_t _mutex;
    };

    //RAII风格，自动析构，无需手动释放资源
    class LockGuard
    {
    public:
        LockGuard(Mutex& mutex):_mutex(mutex)
        {
            _mutex.lock();
        }
        ~LockGuard()
        {
            _mutex.unlock();
        }
    private:
        Mutex& _mutex;
    };
}